package com.fintech.third.task;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.fintech.common.service.BaseServiceImpl;
import com.fintech.third.constant.LocalStatus;
import com.fintech.third.constant.ThirdProductChannelConstant;
import com.fintech.third.constant.ThirdProductConstant;
import com.fintech.third.dao.MessageIndustryMapper;
import com.fintech.third.dao.SmsMapper;
import com.fintech.third.dao.SmsTemplateMapper;
import com.fintech.third.dao.ThirdProductChannelMappper;
import com.fintech.third.dao.sms.SmsLogMapper;
import com.fintech.third.model.ThirdProductChannel;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.message.EnterpriseResponse;
import com.fintech.third.model.message.MessageIndustryDto;
import com.fintech.third.model.message.MicroNetResponse;
import com.fintech.third.model.message.ResponseData;
import com.fintech.third.model.message.SmsSend;
import com.fintech.third.model.message.SmsTemplate;
import com.fintech.third.model.sms.SmsLog;
import com.fintech.third.service.SmsChannelSend;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;


/**
 * 定时发送短信
 * @author tangpw
 *
 */
@Configuration
@EnableScheduling
public class SmsTimingTask extends BaseServiceImpl {
	@Autowired
	private SmsLogMapper smsLogMapper;
	
	@Autowired
	private SmsMapper smsMapper;

	@Autowired
	private MessageIndustryMapper messageIndustryMapper;
	@Autowired
	private ThirdProductChannelMappper thirdProductChannelMappper;

	@Autowired
	private SmsTemplateMapper smsTemplateMapper;
	//	@Scheduled(cron = "0 0 18 * * ? ") // 每天下午6点触发
	@Scheduled(cron="0 0/5 *  * * ? ")
	public void smsTimingTask() {
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date startDate = new Date();
		String thirdMethodConstants = null; // 接口名
		
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		MarvelsLogUtil.getInstance().info("=================定时发送短信开始=============");
		
		if(Boolean.parseBoolean(thirdProperties.getIs_not_sms_timing_send())){//定时任务不发
			MarvelsLogUtil.getInstance().info("=================不发短信定时任务=============");
			return;
		}
		
		List<SmsSend> list = smsMapper.selectSmsSendList();
		if (null == list || list.size()<1) {
			MarvelsLogUtil.getInstance().info("=================无需要发送的短信=============");
			return;
		}
//		List<SmsSend> strListFail = new ArrayList<SmsSend>();
		boolean isTrueTestSms = false;
		boolean isTencentTestSms = false;
		boolean isMicronetComSms = false;
		boolean isSpeedShield = false;
		boolean isChuangLan=false;
		boolean isMenWang=false;
		boolean isFengHuo=false;
		boolean isEnterprise=false;
		ThirdProductChannel productChannelDto = new ThirdProductChannel();
		productChannelDto = thirdProductChannelMappper.queryAvailableChannel(ThirdProductConstant.SMS.getCode());
		String channelCode=productChannelDto.getCode();
		for (SmsSend smsSend : list) {
			MessageIndustryDto messageIndustryDto=messageIndustryMapper.selectMessageIndustryMapper(ThirdProductConstant.SMS.getCode(),channelCode,smsSend.getTemplate_id()+"");
			boolean bool = false;
			String phone = smsSend.getPhone();
			String templateContent = smsSend.getMsg();
			String messageCategory=messageIndustryDto.getIndustry();
			try {
				SmsTemplate smsTemplate=smsTemplateMapper.obtainSmsTemplateContent(smsSend.getTemplate_id());
				if(smsTemplate!=null && StringUtils.isNotBlank(smsTemplate.getChannel_code())){
					channelCode=smsTemplate.getChannel_code();
				}
				if (productChannelDto != null
						&& ThirdProductChannelConstant.TRUETESTSMS.getCode().equals(channelCode)) {// 中正云通讯短信
					thirdMethodConstants = ThirdProductChannelConstant.TRUETESTSMS.getCode();
					isTrueTestSms = true;
				} else if (productChannelDto != null
						&& ThirdProductChannelConstant.TENCENTSMS.getCode().equals(channelCode)) {// 腾讯云短信
					thirdMethodConstants = ThirdProductChannelConstant.TENCENTSMS.getCode();
					isTencentTestSms = true;
				} else if (productChannelDto != null
						&& ThirdProductChannelConstant.MICRONETCOMSMS.getCode().equals(channelCode)) {// 微网通联短信
					thirdMethodConstants = ThirdProductChannelConstant.MICRONETCOMSMS.getCode();
					isMicronetComSms = true;
				}else if(productChannelDto != null
						&& ThirdProductChannelConstant.SPEEDSHIELD.getCode().equals(channelCode)){//速盾短信
					thirdMethodConstants = ThirdProductChannelConstant.SPEEDSHIELD.getCode();
					isSpeedShield=true;
				}else if(productChannelDto != null
						&& ThirdProductChannelConstant.MENGWANG.getCode().equals(channelCode)){//速盾短信
					thirdMethodConstants = ThirdProductChannelConstant.MENGWANG.getCode();
					isMenWang=true;
				}else if(productChannelDto != null
						&& ThirdProductChannelConstant.FENGHUODX.getCode().equals(channelCode)){//烽火短信
					thirdMethodConstants = ThirdProductChannelConstant.FENGHUODX.getCode();
					isFengHuo=true;
				}else if(productChannelDto != null
						&& ThirdProductChannelConstant.EnterpriseMsg.getCode().equals(channelCode)){//企业短信通短信
					thirdMethodConstants = ThirdProductChannelConstant.EnterpriseMsg.getCode();
					isEnterprise=true;
				}
				if (isTrueTestSms) {
					String string = SmsChannelSend.middleClubSms(phone, templateContent);
					String[] strings = string.split("/");
					if ("000".equals(strings[0])) {
						bool = true;

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = strings[0];
				} else if (isTencentTestSms) {
					ResponseData responseData = null;
					responseData = SmsChannelSend.tencentSms(phone, templateContent);
					MarvelsLogUtil.getInstance().info("send_note_error===>>" + responseData.getError());
					JSONObject result_json = JSONObject.fromObject(responseData.getBody());
					if ("0".equals(result_json.get("result"))) {
						bool = true;

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = result_json.get("result") + "";

				} else if (isMicronetComSms) {
					if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("2"))){//营销
						messageCategory="2";
					}else if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("3"))){//行业通知
						messageCategory="3";
					}else if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("1"))|| (messageIndustryDto==null)){//行业触发
						messageCategory="1";
					}
					MicroNetResponse microNetResponse = SmsChannelSend.microNetcomSms(phone, templateContent,messageCategory);
					if ("0".equals(microNetResponse.getState())) {
						bool = true;
						smsSend.setMsg_bathId(microNetResponse.getMsgID());

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = microNetResponse.getState();
				}else if(isSpeedShield){
					Map<String, String> map=new HashMap<String,String>();
					map.put("mobile",phone);
					map.put("msg", templateContent);
					String result="";
					if(messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("2")){//催收
						map.put("content", templateContent);
						result = SmsChannelSend.SpeedShieldTechnologyCollection(map);
					}else{
						result = SmsChannelSend.SpeedShieldTechnology(map);
					}
					String msgId="";
					if(StringUtils.isNotEmpty(result)){
						String[] strings=new String[1];
						strings=result.split(",");
						String[] string=new String[1];
						string=strings[1].split("\n");
						if(string[0].equals("0")){//成功
							bool=true;
							if(!string[1].equals("collection")){
								msgId=string[1];
							}

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
						} else {
							status = LocalStatus.REQUEST_FAIL.getCode();
						}
						thirdCode = strings[0];
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					smsSend.setMsg_bathId(msgId);
				}else if(isChuangLan){
					Map<String, String> map=new HashMap<String,String>();
					map.put("mobile",phone);
					map.put("msg", templateContent);
					String result="";
					if(!messageCategory.equals("2")){
						messageCategory="1";
					}map.put("messageCategory", messageCategory);
					result=SmsChannelSend.createBuleMsg(map);
					String msgId = "";
					if(StringUtils.isNotEmpty(result)){
						if(StringUtils.isNotEmpty(result)){
							JSONObject jsonResult=JSONObject.fromObject(result);
							if(jsonResult.get("code").equals("0")){//
								bool=true;
								msgId=jsonResult.getString("msgId");

								status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
							} else {
								status = LocalStatus.REQUEST_FAIL.getCode();
							}
							thirdCode = jsonResult.get("code") + "";
						}
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					smsSend.setMsg_bathId(msgId);
				} else if (isMenWang) {// 梦网短信
					MarvelsLogUtil.getInstance().info("===============调用梦网短信方法,手机号:" + phone);
					Map<String, String> map = new HashMap<String, String>();
					map.put("mobile", phone);
					map.put("msg", templateContent);
					if ((messageIndustryDto != null && messageIndustryDto.getIndustry().equals("2"))) {// 会员营销短信
						messageCategory = "2";
					} else {// 验证码通知短信
						messageCategory = "1";
					}
					map.put("messageCategory", messageCategory);
					String result = SmsChannelSend.monternetMsg(map);
					String msgId = "";
					if (StringUtils.isNotEmpty(result)) {
						JSONObject jsonResult = JSONObject.fromObject(result);
						if (jsonResult.getInt("result") == 0) {// 成功
							bool=true;
							msgId = jsonResult.getString("msgid");

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
						} else {
							status = LocalStatus.REQUEST_FAIL.getCode();
						}
						thirdCode = jsonResult.getInt("result") + "";
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					smsSend.setMsg_bathId(msgId);
				}else if (isFengHuo) {// 烽火短信
					MarvelsLogUtil.getInstance().info("===============调用烽火短信方法,手机号:" + phone);
					Map<String, String> map = new HashMap<String, String>();
					map.put("mobile", phone);
					map.put("msg", templateContent);
					if ((messageIndustryDto != null && messageIndustryDto.getIndustry().equals("2"))) {// 会员营销短信
						messageCategory = "2";
					} else {// 验证码通知短信
						messageCategory = "1";
					}
					map.put("messageCategory", messageCategory);
					String result = SmsChannelSend.monternetMsg(map);
					String msgId = "";
					if (StringUtils.isNotEmpty(result)) {
						String[] strings=result.split(":");
						if (strings[0].equals("success")) {// 成功
							msgId = strings[1];
							bool=true;

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
						}  else {
							status = LocalStatus.REQUEST_FAIL.getCode();
						}
						thirdCode = strings[0];
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					smsSend.setMsg_bathId(msgId);
				}else if (isEnterprise) {// 企业短信通短信
					MarvelsLogUtil.getInstance().info("===============调用企业短信通方法,手机号:" + phone);
					Map<String, String> map = new HashMap<String, String>();
					map.put("mobile", phone);
					map.put("msg", templateContent);
					if ((messageIndustryDto != null && messageIndustryDto.getIndustry().equals("2"))) {// 会员营销短信
						messageCategory = "2";
					} else {// 验证码通知短信
						messageCategory = "1";
					}
					map.put("messageCategory", messageCategory);
					EnterpriseResponse enterpriseResponse = SmsChannelSend.EnterpriseMsg(map);
					String msgId = "";
					if (enterpriseResponse!=null && enterpriseResponse.getReturnstatus().equalsIgnoreCase("Success")) {
							msgId = enterpriseResponse.getTaskID();
							bool=true;

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = enterpriseResponse.getReturnstatus();
					smsSend.setMsg_bathId(msgId);
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("==========短息发送异常,短信内容:" ,e);
			}

			if (bool) {// 发送成功
				smsSend.setSend_status("1");
			} else {
				smsSend.setSend_status("-1");
//				smsMapper.deleteSmsSendDetail(smsSend);
//				strListFail.add(smsSend);
			}
			
			smsMapper.updateSmsSendDetail(smsSend);
			
			try {
				//写入sms_log记录   用于计费统计
				SmsLog smsLog=new SmsLog();
				smsLog.setChannelCode(channelCode);
				smsLog.setPhone(phone);
				smsLog.setContent(templateContent);
				smsLog.setSendTime(new Date());
				smsLog.setStatus(smsSend.getSend_status().equals("1")?true:false);
				smsLogMapper.insertSelective(smsLog);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>定时发短信写入短信统计表异常:",e);
			}
			
		}

//		// 开始修改发送状态
//		if (null != strListSuccess && strListSuccess.size()>0) {
//			smsMapper.updateSmsSendList(strListSuccess);
//		}
//		
//		if(null!=strListFail && strListFail.size()>0){
//			smsMapper.insertSmsSendFailureList(strListFail);
//		}

		// 记入统一日志表
		saveDataQueryLog(System.currentTimeMillis() + "_" + RandomStringUtils.randomAlphanumeric(6), null, null, null,
				startDate, new Date(), thirdMethodConstants, thirdCode, status, "edc_sms_data_query_log", "system");

		MarvelsLogUtil.getInstance().info("=================定时发送短信结束=============");

	}

}
